﻿using UnityEngine;
using System.Collections;

public class BrickCoinScript : MonoBehaviour {

	public float jumpUpAmount	=	0.03f;
	public float offset   		=	0.5f;
	public float duration		=	0.2f;
	public Transform aCoin;
	public AudioClip SoundCoin;

	private bool gotHit=false;
	private Vector3 oldPosition;
	// Use this for initialization
	void Start () {
		oldPosition= this.transform.position;
	}
	
	// Update is called once per frame
	void Update () {
		if (gotHit) this.transform.Translate(new Vector2(0,jumpUpAmount));
	}
	void FixedUpdate(){


	}
	void OnCollisionEnter2D(Collision2D collision) {
		if((this.transform.position.y-collision.contacts[0].point.y)>=0.162){
			//change sprite
			BreakBrickAnimation();
			//remove spire

			StartCoroutine ("DisappearBrick",duration);
			//play sound
			if (SoundCoin!=null&&!Camera.current.audio.isPlaying) Camera.current.audio.PlayOneShot(SoundCoin);
			//count score for player
			Camera.current.GetComponent<SystemParameters>().GetCoin(1);

		}
	}

	// move the coin away
	IEnumerator DisappearBrick (float afterSec) {
		yield return new WaitForSeconds(duration);
		var newPosition= aCoin.position;
		newPosition.y= newPosition.y+99f;
		aCoin.position =newPosition ;


		//hide old block
		this.renderer.enabled=false;
		this.collider2D.enabled=false;
		//new Block appear
		gotHit=false;
		this.transform.position=oldPosition;
		var child=this.transform.GetChild(0);
		child.gameObject.SetActive(true);


		
	}
//	IEnumerator BrickHop() {
//		for (int i=0;i<30;i++){
//		this.transform.Translate(new Vector2(0,0.1f));
//		
//		}
//
//
//	}

	
	void BreakBrickAnimation(){

		gotHit=true;
		var newPosition= this.transform.position;
		newPosition.y=newPosition.y + offset;
		aCoin.position = newPosition;


	}

}



		
		